package com.dxy.lc.utils;

import com.dxy.lc.base.UnifiedException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * 对象与JSON相互转换工具API
 *
 * @author Administrator
 */
@Slf4j
public class JsonUtil {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成JSON
     */
    public static String toJSON(Object object) {
        String json = null;
        try {
            json = MAPPER.writeValueAsString(object);
        } catch (Exception e) {
            log.error("对象转Json字符串异常：",e);
            throw new UnifiedException(e);
        }
        return json;
    }

    /**
     * 将JSON转换成对象
     */
    public static <T> T toObject(String json, Class<T> targetClass) {
        T object = null;
        try {
            object = MAPPER.readValue(json, targetClass);
        } catch (Exception e) {
            log.error("Json字符串转对象异常：",e);
            throw new UnifiedException(e);
        }
        return object;
    }
}
